<?php

namespace common\behaviors;

use Closure;
use Yii;
use yii\behaviors\AttributeBehavior;
use yii\db\BaseActiveRecord;

/**
 * 自动记录当前的用户
 *
 * @package common\behaviors
 */
class UserRecordBehavior extends AttributeBehavior
{

    public $userId = null;

    /**
     * @var string
     */
    public $createdByAttribute = 'created_by';

    /**
     * @var string
     */
    public $updatedByAttribute = 'updated_by';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if (empty($this->attributes))
        {
            $this->attributes = [
                BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdByAttribute, $this->updatedByAttribute],
                BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedByAttribute,
            ];
        }
    }

    /**
     * 当前操作用户
     *
     * @return int|string
     */
    public function getUserId()
    {
        if ( ! $this->userId)
        {
            return Yii::$app->user->identity->getId();
        }
        if ($this->userId instanceof Closure)
        {
            return call_user_func($this->userId, $this->owner, $this);
        }
        return $this->userId;
    }

    /**
     * @inheritdoc
     */
    public function evaluateAttributes($event)
    {
        if ( ! empty($this->attributes[$event->name]))
        {
            $userID = $this->getUserId();

            // 设置创建者
            if ($event->name === BaseActiveRecord::EVENT_BEFORE_INSERT && isset($this->owner->{$this->createdByAttribute}))
            {
                $this->owner->{$this->createdByAttribute} = $userID;
            }

            // 设置更新者
            if ($event->name === BaseActiveRecord::EVENT_BEFORE_UPDATE && isset($this->owner->{$this->updatedByAttribute}))
            {
                $this->owner->{$this->updatedByAttribute} = $userID;
            }
        }
    }
}
